import os;
import threading;
import time;

class ClientThread(threading.Thread):
    # Override __init__() method to allow us to do something with the arguments
    def __init__(self,name,inpipe,outpipe):
        threading.Thread.__init__(self, None, None, name);
        self._inpipe=inpipe;
        self._outpipe=outpipe;
        self._name=name;
    # Override the run method
    def run(self):
        data = ['The Knights who say Ni!',
           'Appear in the film "Monty Python and the Holy Grail" ']
        for line in data:
            os.write(self._outpipe,line);
            print os.read(self._inpipe,1024);
        print("client exiting");

class ServerThread(threading.Thread):
    # Override __init__() method to allow us to do something with the arguments
    def __init__(self,name,inpipe,outpipe):
        threading.Thread.__init__(self, None, None, name);
        self._inpipe=inpipe;
        self._outpipe=outpipe;
        self._name=name;
        self.daemon=True;
    # Override the run method
    def run(self):
        ncon=0;
        while ncon<3: # serve only 3 connections.
            data = os.read(self._inpipe,1024)
            data = 'Ni!\n' + data + '\nNi! '+str(ncon);
            os.write(self._outpipe,data)
            ncon+=1;
        print("server exiting");

ServerReceive,ClientSend = os.pipe();
ClientReceive, ServerSend = os.pipe();

server = ServerThread("Hello." ,ServerReceive,ServerSend);
client = ClientThread("Yoyoyo!",ClientReceive,ClientSend);

server.start();
time.sleep(2);
client.start();
